package dao

import (
	"context"
	"mini-app/internal/models"

	"gorm.io/gorm"
)

type UserAddress struct{}

func (UserAddress) Create(
	ctx context.Context,
	db *gorm.DB,
	record models.UserAddress,
) (string, error) {
	err := db.WithContext(ctx).Omit("default").Create(&record).Error
	return record.ID, err
}
func (UserAddress) Delete(
	ctx context.Context,
	db *gorm.DB,
	openid string,
	ID string,
) bool {
	rowsAffected := db.WithContext(ctx).Model(&models.UserAddress{}).
		Where("id = ?", ID).
		Where("openid = ?", openid).
		Delete(&models.UserAddress{}).
		RowsAffected
	return rowsAffected == 1
}
func (UserAddress) Update(
	ctx context.Context,
	db *gorm.DB,
	openid string,
	record models.UserAddress,
) bool {
	rowsAffected := db.WithContext(ctx).Model(&models.UserAddress{}).
		Where("id = ?", record.ID).
		Omit("id", "openid", "default").
		Updates(&record).
		RowsAffected
	return rowsAffected == 1
}

func (UserAddress) List(
	ctx context.Context,
	db *gorm.DB,
	openid string,
) (list []models.UserAddress) {
	db.WithContext(ctx).Model(&models.UserAddress{}).
		Where("openid = ?", openid).
		Select(
			"id",
			"user_name",
			"tel_number",
			"postal_code",
			"province_name",
			"city_name",
			"county_name",
			"street_name",
			"detail_address",
			"default",
		).
		Find(&list)
	if len(list) == 0 {
		return []models.UserAddress{}
	}
	for index := range list {
		list[index].OpenID = ""
	}
	return list
}

// SetDefault 设置默认地址
func (UserAddress) SetDefault(
	ctx context.Context,
	db *gorm.DB,
	openid string,
	addressID string,
) {
	db.WithContext(ctx).Model(&models.UserAddress{}).
		Where("openid = ?", openid).
		Update("default", 2)

	db.WithContext(ctx).Model(&models.UserAddress{}).
		Where("openid = ?", openid).
		Where("id = ?", addressID).
		Update("default", 1)
}

// GetDefault 获取默认地址
func (UserAddress) GetDefault(
	ctx context.Context,
	db *gorm.DB,
	openid string,
) *models.UserAddress {
	var defaultUserAddress models.UserAddress
	rowsAffected := db.WithContext(ctx).Model(&models.UserAddress{}).
		Where("openid = ?", openid).
		Where("`default` = ?", 1).
		Take(&defaultUserAddress).
		RowsAffected
	if rowsAffected <= 0 {
		return nil
	}
	defaultUserAddress.OpenID = ""
	return &defaultUserAddress
}
